package org.ftc.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.ftc.domain.CommitteeTeam;
import org.ftc.domain.Session;
import org.ftc.form.SessionForm;
import org.ftc.service.CommitteeTeamService;
import org.ftc.service.FtcLogService;
import org.ftc.service.FtcLogService.Log;
import org.ftc.service.SessionService;
import org.ftc.service.UsersService;
import org.ftc.util.Global;
import org.ftc.util.ListCalculator;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller 
public class SessionController {
	@Autowired
	UsersService usersService;
	@Autowired
	SessionService sessionService;
	@Autowired
	CommitteeTeamService committeeTeamService;
	@Autowired
	FtcLogService logService;
	
	@RequestMapping(value = "/session.htm")
	public String index(ModelMap model) {
			model.addAttribute("searchForm", new SessionForm() );//
			model.addAttribute("newForm", new Session() );//
		return "session/list";
	}

	@RequestMapping(value = "/session/list.json", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(SessionForm form, BindingResult binding, ModelMap model ){
		logService.before();
		model.put("searchForm", form);
		Map<String, Object> map = new HashMap<String, Object>();
		ListCalculator listCal = new ListCalculator(); 
		int pageSize = form.getRows();
		listCal.setRecordsPerPage( pageSize );
		Integer totalRecs = (int)sessionService.count(form);
		int totalPages = listCal.totalPages(totalRecs);  
		int pageNo = form.getPage();
		pageNo = (pageNo >= totalPages) ? totalPages : pageNo;
		int firstRes = listCal.firstResult(pageNo);  
		map.put("total", totalRecs.toString() ); 
		List<Session> datas = sessionService.findPage(form, firstRes, pageSize);
		map.put("rows", datas);
		logService.save(Log.QUERY, this.getClass().toString() );
		return map; 
	}

	@RequestMapping(value = "/session/newForm.htm")
	public String newForm(ModelMap model) {
		Session session = new Session();
		model.addAttribute("sessionForm", session);
		return "session/save";
	}

	@RequestMapping(value = "/session/save.json", method = RequestMethod.POST)
	public @ResponseBody String save(Session entity, BindingResult binding, ModelMap model) {
		logService.before();
		boolean result = false;
		Date date = entity.getMeetingDate();
		if(date!=null){
			DateTime dt = new DateTime(date);
			entity.setYear(dt.getYear()-1911+"");
			entity.setMonth(dt.getMonthOfYear()+"");
			entity.setDay(dt.getDayOfMonth()+"");
		}
		CommitteeTeam team = committeeTeamService.getChecked();
		if(team==null){
			return "noComm";
		}
		entity.setCommitteeTeam(team.gettCode());
		try{
			result = sessionService.save(entity);
		}catch(Exception e){
			e.printStackTrace();
		}
		logService.save(Log.INSERT, entity.getSessionNo(), this.getClass().toString() ,ToStringBuilder.reflectionToString(entity));
		return result+"";
	}

	@RequestMapping(value = "/session/get.htm")
	public String get(@RequestParam("id") String id, ModelMap model) {
		logService.before();
		Session entity = sessionService.get(id);
		model.addAttribute("sessionForm", entity);
		logService.save(Log.QUERY, this.getClass().toString() );
		return "session/update";
	}

	@RequestMapping(value = "/session/update.json")
	public@ResponseBody Object update(Session entity, BindingResult binding, ModelMap model) {
		logService.before();
		Session session = sessionService.get(entity.getSessionNo());
		Date date = entity.getMeetingDate();
		if(date!=null){
			DateTime dt = new DateTime(date);
			entity.setYear(dt.getYear()-1911+"");
			entity.setMonth(dt.getMonthOfYear()+"");
			entity.setDay(dt.getDayOfMonth()+"");
		}
		entity.setCommitteeTeam(session.getCommitteeTeam());
		boolean result = sessionService.update(entity);
		logService.save(Log.UPDATE, entity.getSessionNo(), this.getClass().toString() ,ToStringBuilder.reflectionToString(entity));
		return result ?entity:false;
	}

	@RequestMapping(value = "/session/delete/{id}.json")
	public @ResponseBody
	boolean delete(@PathVariable String id) {
		if(StringUtils.isBlank(id)){
			return false;
		}
		logService.before();
		logService.save(Log.DELETE, id, this.getClass().toString() );
		return sessionService.delete(id);
	}
	
	@RequestMapping(value = "/session/{id}/findSession.json", method = RequestMethod.GET)
	public @ResponseBody
	List<Session> findSession(@PathVariable String id) {
		return sessionService.findSessions(id);
		
	}

	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(Global.APP.DATE_FORMAT); 
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }	
}
